import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import { getUserInfo } from '@/api/user'
import { getSevenToken, getSevenUpload } from "@/api/release.js";



export default new Vuex.Store({
  //存数据
  state: {
    uid: '',
    token: '',
    userInfo: {},
    ifLongin: false,
    publish_num:0,
    liked_num:0,
  },
  //计算属性
  getters: {
  },
  //改数据
  mutations: {
    Myinfo(state, [key, val]) {
      state[key] = val
    },
    Clear(state) {
      state['uid'] = ''
      state['token'] = ''
      state['userInfo'] = {}
      state['ifLongin'] = false
      state['publish_num'] = 0
      state['liked_num'] = 0


    }

  },
  //调接口
  actions: {
    getUserInfo({ commit }, token) {
      return getUserInfo({
        token
      }).then(res => {
        let { userInfo, token, uid,publish_num,liked_num} = res;
        // 免登录
        commit('Myinfo', ['userInfo', userInfo]);
        commit('Myinfo', ['token', token]);
        commit('Myinfo', ['uid', uid]);
        commit('Myinfo', ['ifLongin', true]);
        commit('Myinfo', ['publish_num', publish_num]);
        commit('Myinfo', ['liked_num', liked_num]);

      })
    },
    async Upload(o,fileList) {
      // 接受fileList [file]组成的数组
      if (!Array.isArray(fileList) || fileList.length === 0) {
        return [];
      }

      // 多图上传
      let task = fileList.map((v) => {
        return new Promise((resolve, rejrct) => {
          //二进制文件
          let file = v.file;
          //生成随机名称
          let { type } = file; //
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          // 获取到一个上传七牛云时的认证token
          getSevenToken().then(({ token }) => {
            // console.log(token)
            const formdata = new FormData();
            formdata.append("file", file);
            formdata.append("token", token);
            formdata.append("key", file_name);

            getSevenUpload(formdata).then((res) => {
              resolve("http://toutiao.longxiaokj.com/" + res.key);
            });
          });
        });
      });

      let imgList = await Promise.all(task)
      return imgList
      // @return[]  上传到服务器的路径
    },



  },
  //模块化
  modules: {

  }
})
